import traceback

from django.core.exceptions import PermissionDenied
from django.http import Http404

from rest_framework import exceptions, status
from rest_framework.views import set_rollback
import logging

from backend.utils.response import ApiResponse

logger = logging.getLogger('log')


def custom_exception(exc, context):
    if isinstance(exc, Http404):
        exc = exceptions.NotFound()
    elif isinstance(exc, PermissionDenied):
        exc = exceptions.PermissionDenied()
    message = "服务器内部错误"
    headers = {}
    if isinstance(exc, exceptions.APIException):
        if getattr(exc, 'auth_header', None):
            headers['WWW-Authenticate'] = exc.auth_header
        if getattr(exc, 'wait', None):
            headers['Retry-After'] = '%d' % exc.wait

        if isinstance(exc.detail, (list, dict)):
            # data = exc.detail
            message = exc.detail
        else:
            # data = {'detail': exc.detail}
            message = exc.detail
    set_rollback()
    try:
        return ApiResponse(code=400, message=message, status=exc.status_code, headers=headers)
    except Exception as e:
        logger.error(traceback.format_exc())
        return ApiResponse(code=400, message=message, status=status.HTTP_500_INTERNAL_SERVER_ERROR, headers=headers)
